<template>
  <ArtTableFullScreen>
    <div class="account-page" :style="{ height: containerMinHeight}" id="table-full-screen">
 	  <ArtRuleSearchForm 
			ref="userArtRuleSearchFormRef"
			:rule="'user-manage-search-form'" 
			:showExpand="true"
			:fetchDatas="getSearchFetchDatas" 
			:options="getSearchFetchOptions"
			@reset="handleReset"
			@search="handleSearch"
	  ></ArtRuleSearchForm> 

      <ElCard shadow="never" class="art-table-card" style="height: calc(100vh - 214px);">
		<div style="height: calc(100% - 0px);">
			<ArtRuleTable 
				ref="userArtRuleTableRef"
				row-key="id"
				rule="user-manage-list" 
				:hideOnSinglePage="false"
				:fetch-data="fetchUserData" 
				:autoLoad="true"
				:customFormatters="customFormatters"
				:customToolBars="getToolBarFormatters"
				paginationAlign="right"
				></ArtRuleTable>
		</div>
        <ElDialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
          width="100%"
          align-center
		  :close-on-click-modal="false"
		  draggable
        >
			<ArtRuleForm  
				ref="artRuleFormRef" 
				:rule="'user-manage-form'" 
				:data="_data" 
				:preview="true" 
				:fetchDatas="getFetchDatas" 
				:options="getFetchOptions"
			/>
          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="dialogVisible = false">取消</ElButton>
              <ElButton type="primary" @click="handleSubmit">提交</ElButton>
            </div>
          </template>
        </ElDialog>
      </ElCard>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { ElDialog, FormInstance, ElTag } from 'element-plus'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormRules } from 'element-plus'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import { UserService } from '@/api/usersApi'
  import { RoleService } from '@/api/sys/roleApi'
  import { OrgService } from '@/api/sys/orgApi'
  import { RuleService } from '@/api/data-rule/ruleApi'
  import ArtRuleTable from '@/components/custom/table/ArtRuleTable.vue'
  import ArtRuleForm from '@/components/custom/forms/ArtRuleForm.vue'
  import ArtRuleSearchForm from '@/components/custom/forms/ArtRuleSearchForm.vue'
  import { useCommon } from '@/composables/useCommon'
  const { containerMinHeight } = useCommon()
  const { width } = useWindowSize()
  defineOptions({ name: 'User' }) // 定义组件名称，用于 KeepAlive 缓存控制

  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const loading = ref(false)

  // 响应式表单数据
  const formFilters = reactive({})

  // 选中的行数据
  const selectedRows = ref<any[]>([])
  // 重置表单
  const handleReset = () => {
	if(userArtRuleSearchFormRef.value){
		userArtRuleSearchFormRef.value.resetForm();
		Object.assign(formFilters, { ...userArtRuleSearchFormRef.value.getFormData() })
		userArtRuleTableRef.value.reset(formFilters)
	}
  }

  // 搜索处理
  const handleSearch = () => {
	if(userArtRuleSearchFormRef.value){
		userArtRuleSearchFormRef.value.resetForm();
		Object.assign(formFilters, { ...userArtRuleSearchFormRef.value.getFormData() })
		userArtRuleTableRef.value.reset(formFilters)
	}
  }

// (-1 注销 0-正常 1-锁定)
const getTagType = (status: string) => {
	switch (status) {
	  case '0':
		return 'success'
	  case '1':
		return 'warning'
	  case '-1':
		return 'danger'
	  default:
		return 'info'
	}
}

// 构建标签文本
const buildTagText = (status: string) => {
	let text = ''
	if (status === '-1') {
		text = '注销'
	} else if (status === '0') {
		text = '正常'
	} else if (status === '1') {
		text = '锁定'
	}else{
		text = '异常'
	}
	return text
}
  
//表单实例
const artRuleFormRef=ref();
const _data=ref<any>({});
const openDialog = async (type: string, row?: any) => {
	dialogVisible.value = true
	dialogType.value = type
	if(artRuleFormRef.value){
		artRuleFormRef.value.resetForm()
	}
	_data.value=row||{};
	if(type === 'edit' && row){
		const data = await UserService.getRoleIds(row.id);
		_data.value.roles=data || []
	}
}

  const userArtRuleSearchFormRef=ref();
  const userArtRuleTableRef=ref();
  // 处理表格行选择变化
  const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
  }
  /**
   * 规则实现
   */
  const fetchUserData = async (): Promise<any[]> => {
    return UserService.pages({
  		query:formFilters,
		pageNumber:userArtRuleTableRef.value.pageNumber,
		pageSize:userArtRuleTableRef.value.pageSize,
      })
  }
  
  const customFormatters = {
    status: (_value:any,row:any) => {
      return h(ElTag, { type: getTagType(row.status) }, () => buildTagText(row.status))
    },
	gender: (_value:any,row:any) => {
		if(row.gender=='1'){
			return '男'
		}
		else if(row.gender=='2'){
			return '女'
		}else{
		  return '-'
		}
	},
	operate: (_value:any,row: any) => {
	  return h('div', [
	    h(ArtButtonTable, {
	      type: 'edit',
		  tip:true,
		  tipContent:'编辑',
	      onClick: () => openDialog('edit', row)
	    }),
	    h(ArtButtonTable, {
	      type: 'delete',
		  tip:true,
		  tipContent:'删除',
	      onClick: () => deleteUser(row)
	    })
	  ])
	}
  }
  
	const getToolBarFormatters = [
  	   {
		   type: 'add',
		   tip:true,
		   tipContent:'新增用户',
		   text:'新增用户',
		   onClick: () => openDialog('add')
	   },
	   {
		   type: 'delete',
		   tip:true,
		   tipContent:'批量删除用户',
		   text:'批量删除用户',
		   onClick: () => deleteUsers()
	   }
	]
  
  const getFetchDatas = {
    roles: async (): Promise<any[]> => {
		return await RoleService.options({})
	},
	orgId:async (): Promise<any[]> => {
		return await OrgService.options({})
	}
  }
  
  const getSearchFetchDatas = {
  	orgIds:async (): Promise<any[]> => {
  		return await OrgService.options({})
  	}
  }
  
  const getFetchOptions = {
    roles:{
		label:'cnName',
		value:'id'
	},
	orgId:{
		children: 'children',
		label: 'label',
		value:'id'
	}
  }
  
  const getSearchFetchOptions = {
  	orgIds:{
  		children: 'children',
  		label: 'label',
  		value:'id'
  	}
  }
  
  const deleteUser =  (row:any) => {
  	ElMessageBox.confirm('确定注销【'+row.cnName+'】用户吗？', '注销用户', {
  		confirmButtonText: '确定',
  		cancelButtonText: '取消',
  		type: 'error'
  	}).then(async () => {
  		loading.value = true
  		try {
  			await UserService.delete(row.id);
  			ElMessage.success('注销用户成功')
			userArtRuleTableRef.value.reload()
  		} catch {
  			ElMessage.error(`注销用户失败`)
  		}finally{
  			loading.value = false
  		}
  	})
  }
  
const handleSubmit = async () => {
	if (!artRuleFormRef.value) return
	if(artRuleFormRef.value.validate()){
		loading.value = true
		try {
			await UserService.save(artRuleFormRef.value.getFormData());
			const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
			ElMessage.success(message)
			userArtRuleTableRef.value.reload()
			dialogVisible.value = false
		} catch {
			ElMessage.error(`失败`)
		}finally{
			loading.value = false
		}
	}
}
  
const deleteUsers =  () => {
	if(userArtRuleTableRef.value.selections.length===0){
		  ElMessage.warning('请选择需要注销的用户.')
		  return;
	}
	ElMessageBox.confirm('确定注销【'+userArtRuleTableRef.value.selections.length+'】条用户信息吗？', '批量注销用户', {
	  confirmButtonText: '确定',
	  cancelButtonText: '取消',
	  type: 'warning'
	}).then(async () => {
		loading.value = true
		try {
			await UserService.batchDelete({
				ids: userArtRuleTableRef.value.selections.map((item:any) => item.id)
			});
			userArtRuleTableRef.value.reload()
			ElMessage.success('批量注销用户成功.')
		} catch {
			ElMessage.error(`批量注销用户失败.`)
		}finally{
			loading.value = false
		}
	})
}
  
	onMounted(() => {
	})
</script>

<style lang="scss" scoped>
  .account-page {
    :deep(.user) {
      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 6px;
      }

      > div {
        margin-left: 10px;

        .user-name {
          font-weight: 500;
          color: var(--art-text-gray-800);
        }
      }
    }
  }
</style>
